package com.zan.zanchat.common.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.zan.zanchat.common.websocket.domain.enums.WSReqTypeEnum;
import com.zan.zanchat.common.websocket.domain.vo.req.WSBaseReq;
import com.zan.zanchat.common.websocket.service.WebSocketService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author Zan
 * @Create 2024/3/7 14:41
 * @Description :
 */
@Sharable // 确保这个Handler实例只建立一次
@Slf4j
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private WebSocketService webSocketService;

    /**
     * 连接刚刚可用的时候 - 即未登录的时候，我们要将其的连接状态保存下来
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        webSocketService = SpringUtil.getBean(WebSocketService.class);
        // 连接保存
        webSocketService.connect(ctx.channel());
    }

    /**
     * 客户端主动下线
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        userOffline(ctx.channel());
    }

    /**
     * 与websocket建立连接，当30s没有数据的时候，就会读空闲，并且断开连接
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN);
            if (StrUtil.isNotBlank(token)) {
                webSocketService.authorize(ctx.channel(), token);
                System.out.println("握手完成");
            }
        } else if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) { // 读空闲
                System.out.println("读空闲");
//                ctx.channel().close(); // 断开连接
                // 业务逻辑：用户下线
                userOffline(ctx.channel());
            }
        } /*else if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            System.out.println("握手请求"); // 握手成功后就不是HTTP请求了，因此就无法获取token了
        }*/ // 这一块可以省略，因为已经过时
    }

    /**
     * 用户下线统一处理
     */
    private void userOffline(Channel channel) {
        webSocketService.offline(channel); // 移除channel
        channel.close(); // 断开连接
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exceptionCaught", cause);
        super.exceptionCaught(ctx, cause);
    }

    /**
     * 前端请求的事件
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        WSBaseReq wsBaseReq = JSONUtil.toBean(text, WSBaseReq.class);
        switch (WSReqTypeEnum.of(wsBaseReq.getType())) {
            case LOGIN:
                System.out.println("请求二维码");
                webSocketService.handleLoginReq(ctx.channel());
                // 拿到的是一个TextWebSocketFrame，因此写给前端也得是一个TextWebSocketFrame
//                ctx.channel().writeAndFlush(new TextWebSocketFrame("123"));
                break;
            case HEARTBEAT:
                break;
            case AUTHORIZE:
                webSocketService.authorize(ctx.channel(), wsBaseReq.getData());
                break;
        }
    }

}
